package com.example.social.screen

import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.example.social.R
import com.example.social.item_view.CommentItem
import com.example.social.navigation.Routes
import com.example.social.screen.component.NotThreadList
import com.example.social.utils.SharedPref
import com.example.social.viewmodel.HomeViewModel
import com.example.social.viewmodel.UserViewModel

@Composable
fun ThreadDetailScreen(
    navHostController: NavHostController,
    tid: String
) {
    val homeViewModel: HomeViewModel = viewModel()
    val userViewModel: UserViewModel = viewModel()
    val context = LocalContext.current
    val currentId = SharedPref.getUid(context)

    val thread by homeViewModel.thread.observeAsState(null)
    val user by userViewModel.users.observeAsState(null)
    val comments by homeViewModel.comment.observeAsState(emptyList())

    val followerList by userViewModel.followerList.observeAsState(emptyList())
    //异常处理
    val error by homeViewModel.error.observeAsState()
    val followerIsError by userViewModel.error.observeAsState();
    val isErrorShown by homeViewModel.isErrorShown.observeAsState(false)
    val followerIsErrorShown by userViewModel.isErrorShown.observeAsState(false)

    // 发布评论的输入框
    var commentText by remember { mutableStateOf("") }
    // 控制数据加载只执行一次
    LaunchedEffect(tid) {
        homeViewModel.getThreadsByTid(tid)
        homeViewModel.getComments(tid)
    }
    userViewModel.getFollowers(user!!.uid)
    // 当 thread 不为 null 时，获取用户信息
    LaunchedEffect(thread) {
        thread?.let {
            userViewModel.fetchUser(it.userId)
        }
    }

    // 跳转登录界面
    if (currentId.isEmpty()) {
        navHostController.navigate(Routes.Login.routes) {
            popUpTo(Routes.Home.routes) { inclusive = true }
            launchSingleTop = true
        }
    }

    // 错误信息弹窗
    LaunchedEffect(isErrorShown, error, followerIsError, followerIsErrorShown) {
        if (!isErrorShown && error != null) {
            Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
            homeViewModel.markErrorAsShown() // 标记错误信息已显示
        }
        if (!followerIsErrorShown && followerIsError != null) {
            Toast.makeText(context, followerIsError, Toast.LENGTH_SHORT).show()
            userViewModel.markErrorAsShown() // 标记错误信息已显示
        }

    }

    Scaffold(
        // 底部栏设置为评论输入框
        bottomBar = {
            BottomAppBar(
                containerColor = Color.White,
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedTextField(
                        value = commentText,
                        onValueChange = { commentText = it },
                        placeholder = { Text("请输入评论...") },
                        modifier = Modifier
                            .weight(1f)
                            .padding(end = 8.dp),
                        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Text),
                        singleLine = true
                    )

                    Button(
                        onClick = {
                            if (commentText.isEmpty()) {
                                Toast.makeText(context, "评论不能为空", Toast.LENGTH_SHORT).show()
                            } else {
                                homeViewModel.postComment(thread!!.tid, currentId, commentText)
                                commentText = "" // 清空输入框
                            }
                        },
                        colors = ButtonDefaults.buttonColors(
                            Color(0xFF007AFF),
                            contentColor = Color.White
                        )
                    ) {
                        Text("发布")
                    }
                }
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding) // 留出 bottomBar 的内边距
        ) {
            // 仅当 thread 和 user 数据存在时渲染详细信息
            if (thread != null && user != null) {
                // 用户信息区域，添加左右10dp的内边距
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 10.dp, end = 10.dp, top = 20.dp), // 添加左右10dp内边距
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AsyncImage(
                        model = ImageRequest.Builder(context)
                            .data(user!!.imageurl)
                            .crossfade(true)
                            .error(R.drawable.undraw_male_avatar)
                            .build(),
                        contentDescription = "User Avatar",
                        modifier = Modifier
                            .size(40.dp)
                            .padding(start = 5.dp)
                            .clip(CircleShape),
                        contentScale = ContentScale.Crop,
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Column {
                        Text(
                            text = user!!.nickname ?: "Anonymous",
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.clickable {
                                val route = Routes.OtherUsers.routes.replace("{data}", user!!.uid)
                                navHostController.navigate(route)
                            })
                        Text(text = user!!.username ?: "", color = Color.Gray)
                    }
                    Spacer(modifier = Modifier.weight(1f))
                    Button(onClick = {
                        user?.let {
                            if (currentId == it.uid) {
                                Toast.makeText(context, "你不能关注自己!", Toast.LENGTH_SHORT)
                                    .show()
                            } else if (!followerList.contains(currentId)) {
                                userViewModel.followUsers(currentId, it.uid)
                            } else {
                                userViewModel.unfollowUser(currentId, it.uid)
                            }
                        }
                    }, modifier = Modifier.padding(end = 5.dp)) {
                        Text(text = if (followerList.contains(currentId)) "取消关注" else "关注Ta")
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))

                // 话题内容区域，添加左右10dp的内边距
                Text(
                    text = thread!!.thread,
                    style = TextStyle(fontSize = 16.sp),
                    modifier = Modifier
                        .padding(bottom = 8.dp)
                        .padding(start = 10.dp, end = 10.dp) // 添加左右10dp内边距
                )

                // 如果有图片，显示图片
                if (thread!!.image.isNotEmpty()) {
                    Image(
                        painter = rememberAsyncImagePainter(model = thread!!.image),
                        contentDescription = "Post Image",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(max = 250.dp)
                            .padding(start = 10.dp, end = 10.dp) // 添加左右10dp内边距
                    )
                }

                // 话题内容区域，添加左右10dp的内边距
                Text(
                    text = thread!!.timestamp,
                    style = TextStyle(fontSize = 16.sp),
                    modifier = Modifier
                        .align(Alignment.End)
                        .padding(10.dp) // 添加左右10dp内边距
                )
                //下划线
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 10.dp, bottom = 5.dp)
                        .height(2.dp)
                        .background(Color.LightGray) // 自定义颜色
                )
                // 评论部分
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = "评论",
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier
                        .padding(start = 10.dp, end = 10.dp, bottom = 5.dp)
                )

                if (comments.isEmpty()) {
                    NotThreadList("暂无用户发布评论")
                } else {
                    LazyColumn(modifier = Modifier.fillMaxSize()) {
                        items(comments) { comment ->
                            CommentItem(comment = comment, navHostController)
                        }
                    }
                }
            }
        }
    }
}
